package com.kevin.validation.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@ResponseBody
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<Object, Object> exception(Exception e) {
        log.warn("exception = {}", e.getMessage());
        Map<Object, Object> map = new HashMap<>();
        if (e instanceof BindException) {
            map.put("code", HttpStatus.EXPECTATION_FAILED.value());
            map.put("message", this.format((BindException) e));
        } else {
            map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            map.put("message", e.getMessage());
        }
        return map;
    }

    private String format(BindException e) {
        StringBuilder sb = new StringBuilder("[");
        List<ObjectError> list = e.getAllErrors();
        for (ObjectError item : list) {
            sb.append(item.getDefaultMessage()).append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');
        return sb.toString();
    }

}
